import os
import time
import pymysql

def query(host, user, pwd, network):
    conn = pymysql.connect(host=host, port=3306, user=user, passwd=pwd, db='zabbix')
    cursor = conn.cursor()
    cursor.execute('SELECT count(*) from hosts_groups hg WHERE hg.groupid = {};'.format(network))
    values = -1
    data = cursor.fetchall()
    print(data)
    if len(data) == 1:
        print(len(data), data[0][0])
        values = data[0][0]
    else:
        print('未查询到符合条件的主机')
        return 0

    cursor.close()
    conn.close()

    return values

def sender(server, value):
    host_name = "CusteomSwitch"
    key = "switch.total"
    cmd = 'zabbix_sender -z {} -s {} -k {} -o {}'.format(server, host_name, key, value)
    print(cmd)
    results = os.popen(cmd)
    for line in results:
        print(line)
    

def main():
    zabbix_host = os.getenv("ZABBIX", "")
    zabbix_user = os.getenv("ZABBIX_USER", "")
    mysql_host = os.getenv("MYSQL", "")
    pwd = os.getenv("PASSWORD", "")
    network = os.getenv("NETWORK", "")
    # print(zabbix_host, zabbix_user, mysql_host, pwd, network)

    if zabbix_host == "" or zabbix_user == "" or mysql_host == "" or pwd == "" or network == "":
        print("ENV variables is empty.")
        return
    
    while True:
        value = query(mysql_host, zabbix_user, pwd, network)

        if value > 0:
            sender(zabbix_host, value)
        else:
            print('查询到的主机数为0, 不发送')
        time.sleep(60)

if __name__ == '__main__':
    main()